const { Order, Payment, User, SystemLog } = require('../models');
const { AppError } = require('../middlewares/errorHandler');
const { logger } = require('../utils/logger');
const { v4: uuidv4 } = require('uuid');

class OrderController {
  /**
   * 创建订单
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async createOrder(ctx) {
    const { type, amount, points, items, paymentMethod } = ctx.request.body;
    const userId = ctx.state.user.id;

    // Generate unique order number
    const orderNumber = `ORD${Date.now()}${Math.floor(Math.random() * 1000)}`;

    // Create order
    const order = await Order.create({
      orderNumber,
      userId,
      type,
      amount,
      points,
      items,
      paymentMethod,
      status: 'pending'
    });

    // Log the action
    await SystemLog.create({
      type: 'operation',
      action: 'create_order',
      userId,
      ipAddress: ctx.ip,
      userAgent: ctx.headers['user-agent'],
      description: `Order created: ${orderNumber}`
    });

    ctx.status = 201;
    ctx.body = {
      status: 'success',
      data: { order }
    };
  }

  /**
   * 获取订单列表
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async getOrders(ctx) {
    const userId = ctx.state.user.id;

    const orders = await Order.findAll({
      where: { userId },
      include: [{
        model: Payment,
        attributes: ['id', 'status', 'method', 'amount']
      }],
      order: [['createdAt', 'DESC']]
    });

    ctx.body = {
      status: 'success',
      data: { orders }
    };
  }

  /**
   * 获取单个订单
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async getOrder(ctx) {
    const { id } = ctx.params;
    const userId = ctx.state.user.id;

    const order = await Order.findOne({
      where: { id, userId },
      include: [{
        model: Payment,
        attributes: ['id', 'status', 'method', 'amount', 'transactionId']
      }]
    });

    if (!order) {
      throw new AppError(404, 'Order not found');
    }

    ctx.body = {
      status: 'success',
      data: { order }
    };
  }

  /**
   * 取消订单
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async cancelOrder(ctx) {
    const { id } = ctx.params;
    const userId = ctx.state.user.id;

    const order = await Order.findOne({
      where: { id, userId },
      include: [{ model: Payment }]
    });

    if (!order) {
      throw new AppError(404, 'Order not found');
    }

    if (order.status !== 'pending') {
      throw new AppError(400, 'Order cannot be cancelled');
    }

    // Update order status
    await order.update({
      status: 'cancelled',
      cancelledAt: new Date()
    });

    // Cancel any pending payments
    if (order.Payments.length > 0) {
      await Payment.update(
        { status: 'cancelled' },
        { where: { orderId: id, status: 'pending' } }
      );
    }

    // Log the action
    await SystemLog.create({
      type: 'operation',
      action: 'cancel_order',
      userId,
      ipAddress: ctx.ip,
      userAgent: ctx.headers['user-agent'],
      description: `Order cancelled: ${order.orderNumber}`
    });

    ctx.body = {
      status: 'success',
      message: 'Order cancelled successfully'
    };
  }

  /**
   * 获取用户订单统计
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */ 
  async getUserOrderStats(ctx) {
    const userId = ctx.state.user.id;

    const stats = await Order.findAll({
      where: { userId },
      attributes: [
        'status',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count'],
        [sequelize.fn('SUM', sequelize.col('amount')), 'totalAmount']
      ],
      group: ['status']
    });

    ctx.body = {
      status: 'success',
      data: { stats }
    };
  }

  /**
   * 获取用户订单统计
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async getOrdersByDateRange(ctx) {
    const userId = ctx.state.user.id;
    const { startDate, endDate } = ctx.query;

    const orders = await Order.findAll({
      where: {
        userId,
        createdAt: {
          [sequelize.Op.between]: [new Date(startDate), new Date(endDate)]
        }
      },
      include: [{
        model: Payment,
        attributes: ['status', 'method', 'amount']
      }],
      order: [['createdAt', 'DESC']]
    });

    ctx.body = {
      status: 'success',
      data: { orders }
    };
  }
}

module.exports = new OrderController(); 